package com.newpage.module_gather.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.newpage.module_gather.R;
import com.newpage.module_gather.R2;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.bean.response.RevisionExamQuestionInfo;
import com.wetao.lib_common.bean.response.WrongQuestionInfo;
import com.wetao.lib_common.bean.track.TrackBean;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.QuestionRevisionItem;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdPenUtil;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BitmapUtil;
import com.wetao.lib_common.utils.DownloadUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.hzw.doodle.DoodleColor;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = ConstantArouter.PATH_GATHER_GATHERRPLAYREVISIONACTIVITY)
public class GatherPlayRevisionActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View {

    //{"explainName":"§1.1 集  合第1题-孙群其","questionId":"167646","explainType":"2","explainUrl":"http://newpage-test.oss-cn-hangzhou.aliyuncs.com/2020-11-20/5554_1100_167646_video_1605838896266.mp3,http://newpage-test.oss-cn-hangzhou.aliyuncs.com/2020-11-20/5554_1100_167646_track_1605838896262.txt,http://newpage-test.oss-cn-hangzhou.aliyuncs.com/2020-11-20//storage/emulated/0/Android/data/com.wetao.teachertrain/files/18879216671/marking/explain/5554_1100_167646_0_pic_1605838806854.png,http://newpage-test.oss-cn-hangzhou.aliyuncs.com/2020-11-20//storage/emulated/0/Android/data/com.wetao.teachertrain/files/18879216671/marking/explain/5554_1100_167646_1_pic_1605838850075.png"}

    @Autowired
    int examId;
    @Autowired
    String questionBean;
    @Autowired
    int type;  // 0 错题详情订正  1 订正详情订正
    @Autowired
    String revisionUrl;
    @Autowired
    String revisionTime;


    private static final int HANDLER_TEST_DELAY_TIME = 900;
    private static final int HANDLER_TRACK_DRAWING = 901;
    private static final int HANDLER_TRACK_UNDO = 902;
    private static final int HANDLER_TRACK_LARGE_JUMPING = 903;
    private static final int HANDLER_AGAIN_RECORD_OR_PLAY = 904;

    private Integer studentExamAnswerId;
    private Integer questionId;
    private Integer subjectId;

    @Autowired
    String explainName;
    @Autowired
    String explainUrl;
    @Autowired
    int explainType;
    @Autowired
    int videoTime;

    @BindView(R2.id.tv_revision_explainName)
    TextView tv_explainName;
    @BindView(R2.id.iv_revision_close)
    ImageView iv_close;
    @BindView(R2.id.fl_revision_doodle)
    FrameLayout fl_doodle;
    @BindView(R2.id.iv_revision_playOrPause)
    ImageView iv_playOrPause;
    @BindView(R2.id.tv_revision_playTime)
    TextView tv_playTime;
    @BindView(R2.id.rsb_revision_video_progress)
    RangeSeekBar rsb_video_progress;
    @BindView(R2.id.rsb_revision_audio_progress)
    RangeSeekBar rsb_audio_progress;


    private String voiceDirPath;
    private String ossMp3Path;
    private String localMp3Path;
    private String ossTxtPath;
    private String localTxtPath;


    private static final int handler_time_pre = 30;
    private float handler_time_scale = 1;
    private boolean isWhiteboard = false;
    private boolean isGliding = false;
    private boolean isLargeJumping = false;
    private boolean isDowningTxt = false;
    private boolean is_rsb_touching = false;
    private float rsb_fromUser_value = 0;
    private int fl_width;
    private int fl_height;
    private int fl_cur_height; //画布当前高度
    private float mTemp_x = 0f; //暂存转换后的坐标
    private float mTemp_y = 0f;
    private float m_tran_x = 0f; //轨迹移动的坐标
    private float m_tran_y = 0f; //轨迹移动的坐标

    private boolean isMove = false; //是否笔是移动中

    private double m_scale = 1.41;//点阵纸宽高比  高:宽=1.41
    private int mPic_w = 2149;
    private int mPic_h = 3023;
    private boolean mIsTran_x = false; //是否允许滚动
    private boolean mIsTran_y = false;  //是否允许滚动


    private Disposable disposable;


    protected PowerManager.WakeLock wakeLock;


    private PlayServiceConnection mPlayServiceConnection;
    private PlayService.PlayBinder playBinder;
    private PlayService playService;
    private int mDuration;


    private Bitmap doodle_bitmap;
    private Bitmap small_bitmap;
    private DoodleParams mDoodleParams;
    private IDoodle mDoodle;
    private DoodleView mDoodleView;
    private DoodleOnTouchGestureListener mTouchGestureListener;

    private List<TrackBean> trackBeanList = new ArrayList<>();
    private int trackIndex_prev = 0;
    private int trackIndex_next = 0;
    private int playCurrentPosition_prev = 0;
    private int playCurrentPosition_next = 0;
    private int largeJumpTime = 0;
    private int largeJumpCount = 0;



    AudioManager mAudioManager;
    //最大音量
    int maxVolume;
    //当前音量
    int currentVolume;


    private MyHandler handler;

    static class MyHandler extends Handler {
        WeakReference<GatherPlayRevisionActivity> weakReference;

        public MyHandler(GatherPlayRevisionActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (weakReference.get() == null) {
                return;
            }
            GatherPlayRevisionActivity activity = weakReference.get();
            if (msg.what == HANDLER_AGAIN_RECORD_OR_PLAY) {
                if (activity.isLargeJumping) {
                    return;
                }
                activity.callPlayMusic();

            }
        }
    }

    private ScreenStatusReceiver mScreenStatusReceiver;

    private void registSreenStatusReceiver() {
        mScreenStatusReceiver = new ScreenStatusReceiver();
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mScreenStatusReceiver, screenStatusIF);
    }

    class ScreenStatusReceiver extends BroadcastReceiver {
        String SCREEN_ON = "android.intent.action.SCREEN_ON";
        String SCREEN_OFF = "android.intent.action.SCREEN_OFF";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (SCREEN_ON.equals(intent.getAction())) {
                LogUtils.e("屏幕：SCREEN_ON");
            } else if (SCREEN_OFF.equals(intent.getAction())) {
                LogUtils.e("屏幕：SCREEN_OFF");

                if (playBinder != null) {
                    if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                        callPauseMusic();
                    }
                }
            }
        }
    }

    @Override
    public void setImmersionBar() {
        //hideBottomUIMenu();
        ImmersionBar.with(this).reset();
        ImmersionBar.with(this)
                .transparentBar()
                .fullScreen(true)
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                .init();
    }

    @Override
    public int getLayoutId() {
        return R.layout.gather_play_video_revision_activity;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }


    @Override
    public void init() {

        //禁止息屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //registSreenStatusReceiver(); //不在这里处理，在onStop上处理

        initData();

        rsb_video_progress.setEnabled(false);
        //获取系统的Audio管理者
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //最大音量
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //当前音量
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.i("音量值：maxVolume = " + maxVolume + ", currentVolume = " + currentVolume);
        rsb_audio_progress.setRange(0, maxVolume);
        rsb_audio_progress.setProgress(currentVolume);
        listenerRangeChanged();


    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @OnClick({R2.id.iv_revision_close,
            R2.id.iv_revision_playOrPause
    })
    public void OnViewClicked(View view) {
        if (view.getId() == R.id.iv_revision_close) {
            callStopMusic();
            finish();
        } else if (view.getId() == R.id.iv_revision_playOrPause) {
            LogUtils.i("播放状态哦：" + playBinder.callPlayStatus());
            if (isLargeJumping || isGliding || isDowningTxt) {
                return;
            }
            if (playBinder != null) {
                if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_IDE
                ) {
                    callPlayMusic();
                } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
                    again_recording_or_play();
                } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                    callPauseMusic();
                } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE) {
                    callResumeMusic();
                } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_STOP) {
                }
            }
        }
    }

    private void initData() {

        /*wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "voice");*/

        handler = new MyHandler(this);
        if (revisionUrl!=null){
            String[] paths = revisionUrl.split(",");
            if (paths.length == 2){
                ossMp3Path = paths[0];
                ossTxtPath = paths[1];
            }else{
                ossMp3Path = paths[0];
            }
            LogUtils.e("localTxtPath ==" + localTxtPath + "\r\n" + "ossTxtPath==" + ossTxtPath + "\r\n" +
                    "ossMp3Path==" + ossMp3Path + "localMp3Path==" + localMp3Path);
        }

//        if (ossTxtPath == null || "".equals(ossTxtPath.trim())) {
//            LogUtils.e("出错了：ossTxtPath == null || \"\".equals(ossTxtPath.trim())");
//            finish();
//            return;
//        }

        if (ossMp3Path == null ||"".equals(ossMp3Path.trim())) {
            LogUtils.e("出错了：ossMp3Path == null || \"\".equals(ossMp3Path.trim())");
            finish();
            return;
        }


        Intent bindIntent = new Intent(this, PlayService.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(bindIntent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);


        getWhiteboardPic();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                callPauseMusic();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //callStopMusic();

    }


    @Override
    protected void onDestroy() {
        callStopMusic();
        rxjava_disposable();
        if (mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection);
            mPlayServiceConnection = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }

        if (mScreenStatusReceiver != null) {
            unregisterReceiver(mScreenStatusReceiver);
        }

        super.onDestroy();
        if(playBinder != null) {
            playBinder = null;
        }
        if(playService != null) {
            playService.setCallback(null);
            playService = null;
        }
    }

    private void getWhiteboardPic() {

        fl_doodle.post(new Runnable() {
            @Override
            public void run() {
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtils.i("-----doodle----getWhiteboardPic主线程ID: " + thread1.getName());
                LogUtils.i("-----doodle----getWhiteboardPic当前线程ID: " + thread2.getName());

                fl_width = fl_doodle.getMeasuredWidth();
                fl_height = fl_doodle.getMeasuredHeight();
                small_bitmap = BitmapUtil.ReadBitmapById_4444(GatherPlayRevisionActivity.this, R.drawable.doodle_bk);
                doodle_bitmap = resizeImage(small_bitmap, fl_width, (int) (fl_width * m_scale));

                fl_cur_height = fl_height;


                initDoodleData(false);
                downLoadTxt();
            }
        });
    }

    public Bitmap resizeImage(Bitmap bitmap, int width, int height) {
        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();

        float scaleWidth = ((float) width) / bmpWidth;
        float scaleHeight = ((float) height) / bmpHeight;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }

    private void again_recording_or_play() {

        handler_time_scale = 1;
        isWhiteboard = false;
        isGliding = false;
        isLargeJumping = false;
        isDowningTxt = false;

        fl_doodle.removeAllViews();
        initDoodleData(false);
        if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY
                || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
        ) {
            playBinder.callStopMusic();
        } else if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE) {
            playBinder.callSetPlayStatus(PlayService.STATUS_MUSIC_IDE);
        }
        //mDuration = 0;


        //mWhiteboard_Doodle_bitmap = null;
        //trackBeanList = new ArrayList<>();
        trackIndex_prev = 0;
        trackIndex_next = 0;
        playCurrentPosition_prev = 0;
        playCurrentPosition_next = 0;
        largeJumpTime = 0;

        Message msg = handler.obtainMessage();
        msg.what = HANDLER_AGAIN_RECORD_OR_PLAY;
        handler.sendMessageDelayed(msg, 500);

    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            playBinder = (PlayService.PlayBinder) binder;
            String testData = playBinder.getServiceTestData();
            LogUtils.i(testData);
            playService = playBinder.getService();
            setPlayMusicUrl(ossMp3Path);
            playService.setCallback(new PlayService.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {
                    LogUtils.i(data);
                }

                @Override
                public void onMusicStausChange(final int status) {
                    //setPlayView(status);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtils.i("播放状态：" + status);
                            showMusicStatus();
                            if (playBinder != null) {
                                if (playBinder.callPlayStatus() != PlayService.STATUS_MUSIC_PLAY) {

                                }
                            }
                        }
                    });
                }

                @Override
                public void onCurrentPosition(final int currentPosition, final int duration) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //setCurAndTotalView(bundle);
                            //LogUtils.i("播放时间：" + currentPosition + "/" + duration);
                            tv_playTime.setText(formateTime(currentPosition / 1000) + "/" + formateTime(duration / 1000));
                            playCurrentPosition_next = currentPosition;
                            if (playBinder != null) {
                                if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY) {
                                } else {
                                    if (currentPosition == 0) {
                                        if (duration != 0) {
                                            mDuration = duration;
                                        }
                                    }
                                }
                            }
                            if (duration > 0 && currentPosition <= duration && !is_rsb_touching) {
                                rsb_video_progress.setProgress(currentPosition * rsb_video_progress.getMaxProgress() / duration);
                            }
                        }
                    });
                }

                @Override
                public void OnDuration(int duration) {
                    LogUtils.i("总时长：" + duration);
                }

                @Override
                public void onLoadedUrl() {

                }

                @Override
                public void onCompletion() {
                    delay_rxjava_disposable();
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    private void setPlayMusicUrl(String url) {
        if (playBinder != null) {
            playBinder.callSetmUrl(url);
        }
    }


    private void callPlayMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_IDE
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_COMPLETE
            ) {
                //lineReadFile();
                playBinder.callPlayMusic();
                drawTrack_rxJava();
            }
        }
    }

    private void callPauseMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY
            ) {
                playBinder.callPauseMusic();
            }
        }
    }

    private void callResumeMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callResumeMusic();
            }
        }
    }

    private void callStopMusic() {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callStopMusic();
                delay_rxjava_disposable();
            }
        }

    }

    private void callPlaySpeed(float speed) {
        if (isLargeJumping) {
            return;
        }
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY
            ) {
                handler_time_scale = speed;
                playBinder.callPlaySpeed(speed);
                rxjava_disposable();
                drawTrack_rxJava();
            }
        }
    }

    private void callSeekTo(int position) {
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
            ) {
                playBinder.callSeekTo(position);
            }
        }
    }

    private void largeJump(int time) {
        if (isLargeJumping || isGliding) {
            return;
        }
        if (playBinder != null) {
            if (playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PLAY
                    || playBinder.callPlayStatus() == PlayService.STATUS_MUSIC_PAUSE
            ) {

                rxjava_disposable();
                largeJumpTime = time;
                isLargeJumping = true;
                handler_time_scale = 10;
                rsb_video_progress.setEnabled(false);
                LogUtils.i("跳转 largeJumpTime = " + largeJumpTime);
                callPauseMusic();
                drawTrack_rxJava();
            }
        }
    }

    private void showMusicStatus() {
        if (playBinder != null) {
            switch (playBinder.callPlayStatus()) {
                case PlayService.STATUS_MUSIC_IDE_PRE: {
                    //tv_playStatus.setText("初始化之前");
                    iv_playOrPause.setImageResource(R.drawable.common_video_start);
                    rsb_video_progress.setEnabled(false);
                    rsb_video_progress.setProgress(0);
                    is_rsb_touching = false;
                }
                break;
                case PlayService.STATUS_MUSIC_IDE: {
                    //tv_playStatus.setText("初始化");
                    iv_playOrPause.setImageResource(R.drawable.common_video_start);
                    rsb_video_progress.setEnabled(false);
                    rsb_video_progress.setProgress(0);
                    is_rsb_touching = false;
                }
                break;
                case PlayService.STATUS_MUSIC_PLAY: {
                    //tv_playStatus.setText("播放");
                    iv_playOrPause.setImageResource(R.drawable.common_video_pause);
                    rsb_video_progress.setEnabled(true);
                }
                break;
                case PlayService.STATUS_MUSIC_PAUSE: {
                    //tv_playStatus.setText("暂停");
                    iv_playOrPause.setImageResource(R.drawable.common_video_start);
                    rsb_video_progress.setEnabled(true);
                }
                break;
                case PlayService.STATUS_MUSIC_STOP: {
                    //tv_playStatus.setText("停止");
                    iv_playOrPause.setImageResource(R.drawable.common_video_start);
                    rsb_video_progress.setEnabled(false);
                    rsb_video_progress.setProgress(0);
                    is_rsb_touching = false;
                }
                break;
                case PlayService.STATUS_MUSIC_COMPLETE: {
                    //tv_playStatus.setText("播放完成");
                    iv_playOrPause.setImageResource(R.drawable.common_video_start);
                    rsb_video_progress.setEnabled(false);
                    rsb_video_progress.setProgress(0);
                    is_rsb_touching = false;
                }
                break;
            }
        }
    }


    private void initDoodleData(boolean isPlay) {
        fl_doodle.removeAllViews();
        mDoodleParams = new DoodleParams();
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;


        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */

        mDoodle = mDoodleView = new DoodleViewWrapper(this, doodle_bitmap, mDoodleParams.mOptimizeDrawing, true, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtils.i("-----doodle----onSaved");
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtils.i("-----doodle----doodleViewWrapper主线程ID: " + thread1.getId());
                LogUtils.i("-----doodle----doodleViewWrapper当前线程ID: " + thread2.getId());
            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtils.i("-----doodle----onReady");
            }
        });

        mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {

            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {

            }

            @Override
            public void onCallScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            }
        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };

        mTouchGestureListener.setSupportScale(false); //禁止放大缩小

        mTouchGestureListener.setSupportDoodle(false); //禁止涂鸦
        mTouchGestureListener.setSupportTrans(false);

        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);
        mDoodleView.setStartXy(true);
        mDoodleView.setColor(new DoodleColor(Color.BLACK));

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        fl_doodle.addView(mDoodleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);
        mDoodle.setZoomerScale(0.79f);
        //mDoodle.setSize(2);

        if (isPlay) {
            drawTrack_rxJava();
        }
    }

    /**
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态
     */
    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, boolean isMask, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, isMask, listener);
        }
    }


    private void lineReadFile() {
        if (localTxtPath == null || "".equals(localTxtPath.trim())) {
            LogUtils.e("注意：localTxtPath == null || \"\".equals(localTxtPath.trim())");
            isDowningTxt = false;
            return;
        }
        File file = new File(localTxtPath);
        if (!file.exists()) {
            LogUtils.e("注意：!file.exists()");
            isDowningTxt = false;
            return;
        }
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                try {
                    trackBeanList.clear();
                    trackIndex_prev = 0;
                    trackIndex_next = 0;
                    FileReader fr = new FileReader(localTxtPath);
                    BufferedReader br = new BufferedReader(fr);
                    String line = "";

                    while ((line = br.readLine()) != null && !"".equals(line.trim()) && JsonUtils.isGoodJson(line)) {
                        TrackBean trackBean = JsonUtils.fromJson(line, TrackBean.class);
                        trackBeanList.add(trackBean);
                    }
                    //LogUtils.i(trackBeanList.toString());
                    br.close();
                    fr.close();
                    //testTrackEvent();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(new Throwable("读取轨迹文件失败！！" + e.getMessage()));
                    emitter.onComplete();
                } finally {
                    emitter.onNext(true);
                    emitter.onComplete();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean aBoolean) {
                //playBinder.callPlayMusic();
                LogUtils.i("读取文件成功");
                if (trackBeanList.size() > 0) {
                    LogUtils.e("注意，trackBeanList.size()= " + trackBeanList.size());
                    //drawTrack_rxJava();
                } else {
                    LogUtils.e("注意，trackBeanList.size()==0");
                }

            }

            @Override
            public void onError(Throwable e) {
                LogUtils.e("出错了，读取轨迹文件失败");
            }

            @Override
            public void onComplete() {
                isDowningTxt = false;
            }
        });
    }


    private void scrollBitmap(TrackBean mCurDot) {

        float temp_y = TsdPenUtil.getRealX(mCurDot.getY(), mPic_h) * mDoodleView.getZoomerScale();
        LogUtils.i("m1: 滚动坐标到x=" + m_tran_x + ", y = " + temp_y + "big_w=" + mDoodleView.getWidth() + "big_h=" + mDoodleView.getHeight());
        if (temp_y > (2 * mDoodleView.getHeight()) && fl_cur_height <= (2*mDoodleView.getHeight()))
        {
//            LogUtils.e("倍数：" + 3 );
            fl_cur_height = mDoodleView.getHeight() * 3;
            mIsTran_y = true;
        }else if (temp_y > mDoodleView.getHeight() && temp_y < (2*mDoodleView.getHeight())
                &&  fl_cur_height != (2*mDoodleView.getHeight())){
//            LogUtils.e("倍数：" + 2 );
            fl_cur_height = mDoodleView.getHeight() * 2;
            mIsTran_y = true;
        }else if (temp_y < mDoodleView.getHeight() && fl_cur_height > mDoodleView.getHeight()){
//            LogUtils.e("倍数：" + 1 );
            fl_cur_height = mDoodleView.getHeight();
            mIsTran_y = true;
        }

        if (mIsTran_y && !isMove){
            mIsTran_y = false;
            m_tran_y = fl_cur_height - mDoodleView.getHeight();
            LogUtils.e("倍数：" + "滚动距离=="  + -m_tran_y + "最终滚动==" + -m_tran_y);
            mTouchGestureListener.setDoodleTranslationXY(0,-m_tran_y);

        }
    }


    private void drawTrack_real() {
        if (trackIndex_prev >= trackBeanList.size()) {
            LogUtils.i("出错了：trackIndex_prev >= trackBeanList.size()");
            rxjava_disposable();
            return;
        }
        TrackBean trackBean = trackBeanList.get(trackIndex_prev);
        scrollBitmap(trackBean);
        trackIndex_prev++;



        mTemp_x = TsdPenUtil.getRealX(trackBean.getX(), mPic_w) * mDoodleView.getZoomerScale();
        mTemp_y = TsdPenUtil.getRealY(trackBean.getY(), mPic_h) * mDoodleView.getZoomerScale() - m_tran_y;
         if ("ACTION_DOWN".equals(trackBean.getAction())) {
             isMove = false;
            mTouchGestureListener.r_onDown(mTemp_x, mTemp_y);
            mTouchGestureListener.r_onScrollBegin(mTemp_x, mTemp_y);
        } else if ("ACTION_MOVE".equals(trackBean.getAction())) {
             isMove = true;
            mTouchGestureListener.r_onScroll(mTemp_x, mTemp_y);

        } else if ("ACTION_UP".equals(trackBean.getAction())) {
             isMove = false;
            mTouchGestureListener.r_onScrollEnd(mTemp_x, mTemp_y);
        }

    }

    private void drawTrack_rxJava() {
        rxjava_disposable();

        Observable.interval(handler_time_pre * 10, (int) (handler_time_pre / handler_time_scale), TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.single())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        //LogUtils.i("测试1");
                        /*if(isPx30Eink) {
                            drawTrack_rxJava_next();
                        } else {*/
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                drawTrack_rxJava_next();
                            }
                        });
                        //}
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void drawTrack_rxJava_next() {
        if (isGliding) {
            return;
        }
        //LogUtils.i("测试2--trackIndex_prev = " + trackIndex_prev + ", trackIndex_next = " + trackIndex_next);
        if (trackIndex_prev == trackIndex_next) {
            int next_time = 0;
            if (isLargeJumping) {
                next_time = largeJumpTime;
            } else {
                next_time = playCurrentPosition_next;
            }
            final int seekTime = next_time;
            //LogUtils.i("测试3--next_time = " +next_time + ", playCurrentPosition_prev = " + playCurrentPosition_prev);
            if (playCurrentPosition_prev <= next_time) {
                //LogUtils.i("测试4--trackBeanList.size() = " + trackBeanList.size());
                if (trackIndex_next < trackBeanList.size()) {
                    //LogUtils.i("测试5");
                    String action = "";
                    for (int i = trackIndex_next; i < trackBeanList.size(); i++) {
                        //LogUtils.i("测试6");
                        TrackBean trackBean = trackBeanList.get(i);
                        if (trackBean.getTime() <= next_time) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            //LogUtils.i("测试7--trackIndex_next = " + trackIndex_next);
                        } else if ("ACTION_DOWN".equals(action) || "ACTION_MOVE".equals(action)) {
                            trackIndex_next = i + 1;
                            action = trackBean.getAction();
                            //LogUtils.i("测试8--trackIndex_next = " + trackIndex_next);
                        } else {
                            //LogUtils.i("测试9");
                            break;
                        }
                    }
                }
            }
            //LogUtils.i("测试10--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
            if (trackIndex_prev == trackIndex_next) {
                //LogUtils.i("测试11");
                if (isLargeJumping) {
                    //LogUtils.i("测试17");
                    isLargeJumping = false;
                    rsb_video_progress.setEnabled(true);
                    largeJumpCount = 0;
                    handler_time_scale = 1;
                    rxjava_disposable();
                    drawTrack_rxJava();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callSeekTo(seekTime);
                            callResumeMusic();
                        }
                    });
                }
                if (trackIndex_next == trackBeanList.size()) {
                    //LogUtils.i("测试12");
                    rxjava_disposable();
                }
                return;
            } else {
                if (trackIndex_next >= trackBeanList.size()) {
                    playCurrentPosition_prev = mDuration;
                } else {
                    playCurrentPosition_prev = trackBeanList.get(trackIndex_next).getTime();
                }

                //LogUtils.i("测试14--playCurrentPosition_prev = " + playCurrentPosition_prev);
            }


        }
        //LogUtils.i("测试15--trackIndex_prev=" + trackIndex_prev + ", trackIndex_next=" + trackIndex_next);
        if (trackIndex_prev > trackIndex_next) {
            LogUtils.e("出错了，trackIndex_prev > trackIndex_next");
            rxjava_disposable();
            return;
        }
        //LogUtils.i("线程时间：" + (System.currentTimeMillis() - PlayService.testTime_2) + ", 线程名：" + Thread.currentThread().getName());
        //PlayService.testTime_2 = System.currentTimeMillis();
        if (trackIndex_prev >= trackBeanList.size()) {
            rxjava_disposable();
        }
        drawTrack_real();
    }

    private void rxjava_disposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    private void delay_rxjava_disposable() {
        Observable.just(1)
                .delay(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        rxjava_disposable();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void delay_largeJumpCountMax() {
        Observable.just(1)
                .delay(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer integer) {
                        drawTrack_rxJava_next();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void downLoadTxt() {
        if (ossMp3Path == null || "".equals(ossMp3Path.trim())) {
            LogUtils.e("注意：ossTxtPath == null || \"\".equals(ossTxtPath.trim())");
            return;
        }

        fileOperate();
        if (localTxtPath != null && !"".equals(localTxtPath.trim())) {
            File file = new File(localTxtPath);
            if (file.exists()) {
                lineReadFile();
                return;
            }
        }

        //无笔迹订正地址直接返回
        if (ossTxtPath==null){
            return;
        }
        isDowningTxt = true;
        DownloadUtil.get().download(this, ossTxtPath, voiceDirPath,localTxtPath, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String path) {
                LogUtils.e("下载txt文件成功 path ==" + path);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        lineReadFile();
                    }
                });
            }

            @Override
            public void onDownloading(final int sum, final int total, final int progress) {

            }

            @Override
            public void onDownloadFailed() {
                LogUtils.e("下载txt文件失败");
                isDowningTxt = false;
            }

            @Override
            public void onNetwork(boolean isNetwork) {
                LogUtils.e("下载txt文件成功-网络连接断开");
                isDowningTxt = false;
                deleteFile(new File(localTxtPath));
            }
        });
    }

    private boolean fileOperate() {
        if (!FileUtils.isSdcardExist()) {
            LogUtils.i("SD卡不存在");
            return false;
        }
        //String dirPath = getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        String mobile = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        if (StringUtil.isEmpty(mobile)) {
            LogUtils.e("出错了，手机号码不能为空");
            return false;
        }

        String voiceDirPath_temp = dirPath + File.separator + mobile + File.separator + "revision";
        File voiceDir = new File(voiceDirPath_temp);
        if (!voiceDir.exists()) {
            boolean mkdirs = voiceDir.mkdirs();
            if (!mkdirs) {
                LogUtils.e("创建失败voiceDir：" + mkdirs);
                return false;
            } else {
                LogUtils.i("创建成功voiceDir");
            }
        }
        voiceDirPath = voiceDirPath_temp;
        //无笔迹订正
        if (ossTxtPath!=null){
            localTxtPath = voiceDirPath + File.separator + ossTxtPath.substring(ossTxtPath.lastIndexOf("/") + 1,ossTxtPath.lastIndexOf("_")) + ".txt";
        }
        localMp3Path = voiceDirPath + File.separator + ossMp3Path.substring(ossMp3Path.lastIndexOf("/") + 1,ossMp3Path.lastIndexOf("_")) + ".mp3";
        return true;
    }

    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        SPUtils.getInstance().put(Constants.UPGRADE_DIALOG_TIME, 0L, true);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            //file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    private String formateTime(int time) {
        String str_t = "";
        int min = time / 60;
        if (min >= 10) {
            str_t += min;
        } else {
            str_t += "0" + min;
        }
        int sec = time % 60;
        str_t += ":";
        if (sec >= 10) {
            str_t += sec;
        } else {
            str_t += "0" + sec;
        }
        return str_t;


    }

    private void listenerRangeChanged() {
        rsb_video_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {

                if (isFromUser) {
                    LogUtils.i("rsb_video_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);
                    rsb_fromUser_value = leftValue;
                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {
                LogUtils.i("rsb_video_progress: onStartTrackingTouch -- isLeft = " + isLeft);
                is_rsb_touching = true;
                rsb_fromUser_value = 0;
            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                LogUtils.i("rsb_video_progress: onStopTrackingTouch -- isLeft = " + isLeft);
                if (rsb_fromUser_value / rsb_video_progress.getMaxProgress() * mDuration <= playCurrentPosition_next) {
                    if (mDuration > 0 && playCurrentPosition_next <= mDuration) {
                        rsb_video_progress.setProgress(playCurrentPosition_next * rsb_video_progress.getMaxProgress() / mDuration);
                    }
                } else {
                    if (rsb_fromUser_value / rsb_video_progress.getMaxProgress() * mDuration - playCurrentPosition_next < 1 * 1000) {
                        LogUtils.e("时长的95%减当前时间小于10秒，不做拖动到95%");
                    } else {
                        largeJump((int) (rsb_fromUser_value / rsb_video_progress.getMaxProgress() * mDuration));
                    }
                }
                is_rsb_touching = false;

            }
        });

        rsb_audio_progress.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if (isFromUser) {
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);
                    currentVolume = (int) leftValue;
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
    }
}
